﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using FwProject.Authorization.Users;
using FwProject.Distribution.Dto;
using X.PagedList;

namespace FwProject.Distribution
{
    /// <summary>
    /// 配送历史查询
    /// </summary>
    public class DistributionHistoryAppService : FwProjectAppServiceBase, IDistributionHistoryAppService
    {
        private readonly IRepository<DistributionHistory, Guid> _repositoryDistributionHistory;
        private readonly IRepository<User, long> _repositoryUser;

        public IGuidGenerator _guid { get; set; }//guid 对象
        public IObjectMapper _map { get; set; }//缓存对象

        public DistributionHistoryAppService(IRepository<DistributionHistory, Guid> repositoryDistributionHistory, IRepository<User, long> repositoryUser)
        {
            _repositoryDistributionHistory = repositoryDistributionHistory;
            _repositoryUser = repositoryUser;
        }

        public async Task<IPagedList<DistributionHistoryDto>> GetPagedListAsync(Guid id,int pageIdx, int pageSize, long? userId, DateTime? beginTime, DateTime? endTime)
        {
            var model = _repositoryDistributionHistory.GetAllIncluding(o => o.DistributionInfoModel).Where(o=>o.DistributionId==id).AsQueryable();

            var data = model.Join(_repositoryUser.GetAll(), a => a.OperatingUserId, b => b.Id, (a, b) => new DistributionHistoryDto
            {
                Id = a.Id,
                OperatingUserId = b.Id,
                OperatingUser = b.Name,
                DistributionId = a.DistributionId,
                DistributionInfoModel = _map.Map<DistributionDto>(a.DistributionInfoModel),
                Record = a.Record,
                OperatingTime = a.CreationTime
            });

            if (userId.HasValue)
                data = data.Where(o=>o.OperatingUserId==userId);
            if (beginTime.HasValue)
                data = data.Where(o=>o.OperatingTime>=beginTime);
            if (endTime.HasValue)
                data = data.Where(o=>o.OperatingTime<=endTime.Value.AddHours(24));

            return await data.OrderByDescending(o => o.OperatingTime).ToPagedListAsync(pageIdx,pageSize);
        }
    }
}
